//
//  LSEmoticonView.swift
//  新浪微博---01次
//
//  Created by 李宗帅 on 16/5/12.
//  Copyright © 2016年 LS. All rights reserved.
//

import UIKit
import SnapKit

let LSCollectionViewReuseIdentifier = "LSCollectionViewReuseIdentifier"
class LSEmoticonView: UIView ,UICollectionViewDataSource,LSEmotionStatckViewDelegate,UICollectionViewDelegate{


    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
        
        setupCollectionView()
    }
    
    

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        addSubview(collectionView)
        addSubview(footerView)
        
        //设置约束
        collectionView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(self)
            
            make.bottom.equalTo(footerView.snp_top)
        }
        
        footerView.snp_makeConstraints { (make) -> Void in
            make.bottom.left.right.equalTo(self)
            
            make.height.equalTo(44)
        }
        
    }
    
    //加载collectionView
    private func setupCollectionView(){
        
        //设置数据源代理
        collectionView.dataSource = self
        
        collectionView.delegate = self
        
        //注册Cell
        collectionView.registerClass(LSCollectionViewCell.self, forCellWithReuseIdentifier: LSCollectionViewReuseIdentifier)
        
        
        
        //设置分页显示
        collectionView.pagingEnabled = true
        
        //隐藏滚动条
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.showsVerticalScrollIndicator = false
        
        //把弹簧效果除去
        collectionView.bounces = false
        
        //设置滚动方向
        flowLayout.scrollDirection = .Horizontal
        
        //设置间距
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.minimumLineSpacing = 0
        
        //设置大小
//        flowLayout.itemSize = collectionView.frame.size
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.5)), dispatch_get_main_queue()) { () -> Void in
            
            // 可不可以让他滚一次
            let path = NSIndexPath(forItem: 0, inSection: 1)
            self.collectionView.scrollToItemAtIndexPath(path, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        }
    }
    
    
    //布局的时候设置大小
    override func layoutSubviews() {
        super.layoutSubviews()
        
        
        flowLayout.itemSize = collectionView.frame.size
    }
    

    //懒加载
    private lazy var collectionView :UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.flowLayout)
    
    private lazy var flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    private lazy var footerView: LSEmotionStatckView = {
       
        let footer = LSEmotionStatckView(frame: CGRectZero)
        
        footer.delegate = self
    
        
        return footer
        
    }()
    
}

extension LSEmoticonView {
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return LSEmoticonManager.getAllEmoticon().count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return LSEmoticonManager.getAllEmoticon()[section].count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(LSCollectionViewReuseIdentifier, forIndexPath: indexPath) as! LSCollectionViewCell
        
        cell.emoticons = LSEmoticonManager.getAllEmoticon()[indexPath.section][indexPath.row]
        
        
        return cell
    }
    
    func didEmotionSelectedSecion(type: LSEmoticonType) {
        
        switch(type){
            
        case .Recent:
            let index = NSIndexPath(forItem: 0, inSection: 0)
            collectionView.scrollToItemAtIndexPath(index, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
            
        case .Default:
            let index = NSIndexPath(forItem: 0, inSection: 1)
            collectionView.scrollToItemAtIndexPath(index, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
            
        case .Emoji:
            let index = NSIndexPath(forItem: 0, inSection: 2)
            collectionView.scrollToItemAtIndexPath(index, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
            
        case .Lxh:
            let index = NSIndexPath(forItem: 0, inSection: 3)
            collectionView.scrollToItemAtIndexPath(index, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        }
    }
    
    
    
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        let visible = collectionView.visibleCells()
        
        //        printLog(scrollView.contentOffset.x)
        
        if visible.count == 2 {
            
            // 再去计算 哪个占的多
            let firstCell = visible.first!
            let secondCell = visible.last!
            
            let firstMargin =  abs(Int32(scrollView.contentOffset.x - firstCell.frame.origin.x))
            let secondMargin = abs(Int32(scrollView.contentOffset.x - secondCell.frame.origin.x))
            
            
            printLog("first = \(firstMargin)")
            
            printLog("second = \(secondMargin)")
            
            // 谁大显示谁
            if firstMargin > secondMargin {
                
                // 显示 firstcell所对应的 section
                let index = collectionView.indexPathForCell(firstCell)!
                printLog(index.section)
                footerView.showSelectedButton(index.section)
                
            } else {
                
                // 显示 firstcell所对应的 section
                let index = collectionView.indexPathForCell(secondCell)!
                printLog(index.section)
                footerView.showSelectedButton(index.section)
                
            }
            
        }
        
    }
    
    //
    //    func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
    //
    //       let section = indexPath.section
    //
    //        footerView.showSelectedButton(section)
    //
    //    }
}





class LSCollectionViewCell: UICollectionViewCell{
    
    // 定义一个表情数组,用于传值
    var emoticons: [LSEmoticon]?{
        
        didSet{
            
            //            print(emoticons?.count)
            // 在解决问题的时候,可以 针对现象去解决,解决完了之后,再去解决由于解决这个问题导致的其它问题
            
            // 让按钮全部隐藏
            for button in buttons{
                button.hidden = true
            }
            
            // 获取到表情model
            // 根据模型显示数据
            for (index,emoticon) in emoticons!.enumerate(){
                // 当你走这个for 循环的时候,显示就行了
                
                //                print("\(emoticon.png)")
                // 应该拿到 cell的 button
                // 按钮顺序那 数组里的按钮
                let button = buttons[index]
                
                button.emoticon = emoticon
                // 要知道他的包命
                
                button.hidden = false
            }
            
            
            //            // 因为最近里 数组是 0
            //            // 所以 for 循环里没有走, 原来设置的 title 或者 image是不是还在
            //
            //            if emoticons?.count == 0{
            //                // 让按钮全部隐藏
            //                for button in buttons{
            //                    button.hidden = true
            //                }
            //
            //            }
        }
        
    }

    // 定义一个数组用来盛放button
    private lazy var buttons: [LSEmoticonButton] = [LSEmoticonButton]()

    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    private func setupUI(){
        backgroundColor = UIColor.whiteColor()
        
//        contentView.addSubview(label)
//        
//        label.snp_makeConstraints { (make) -> Void in
//            make.center.equalTo(contentView)
//        }
        
        addChildButtons()

        
    }
    
    
    private func addChildButtons(){
        
        let childButtonWidth = self.bounds.width / CGFloat(LSEmoticonCol)
        let childButtonHeight = self.bounds.height / CGFloat(LSEmoticonRow)
        
        for i in 0..<LSEmoticonNum{
            
            let button = LSEmoticonButton(type: UIButtonType.Custom)
            
            // 设置属性
            button.addTarget(self, action: "emoticonButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            // 用于测试
            //            button.setTitle("\(i)", forState: UIControlState.Normal)
            //            button.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
            button.titleLabel?.font = UIFont.systemFontOfSize(36)
            
            let col = i % LSEmoticonCol
            let row = i / LSEmoticonCol
            
            // 最关键的是 frame
            button.frame.size = CGSizeMake(childButtonWidth, childButtonHeight)
            button.frame.origin.x = childButtonWidth * CGFloat(col)
            button.frame.origin.y = childButtonHeight * CGFloat(row)
            
            contentView.addSubview(button)
            
            // 添加到数组里,供我们在给他赋值
            buttons.append(button)
        }
        
        // 设置删除按钮的位置
        deleteButton.frame.size = CGSizeMake(childButtonWidth, childButtonHeight)
        deleteButton.frame.origin.x = self.bounds.width - childButtonWidth
        deleteButton.frame.origin.y = self.bounds.height - childButtonHeight
        
        contentView.addSubview(deleteButton)
    }
    
    //MARK:-- 表情按钮的点击 button 是唯一的突破口
    // button 怎么和 emoticon关联起来
    
    @objc private func emoticonButtonClick(button: LSEmoticonButton){
        
        // 所有回答: 闭包和代理的同学你课下的时候用代码去实现一下!!!
        
        // 通知 -- 要传值 , 把 图片或者文字 就把 emoticon传过去
        //        button.titleLabel?.text
        //        button.imageView?.image
        // 可以
        if let emoticon = button.emoticon{
            
            NSNotificationCenter.defaultCenter().postNotificationName(kNotificationEmoticonTransform, object: nil, userInfo: ["key":emoticon])
            
            
            // 把点击的表情,添加到 最近数组里
            // 建议大家 公开方法,供外界调用
            //            HMEmoticonManager.recentEmoticon.append(emoticon)
            LSEmoticonManager.addRecent(emoticon)
        }
        
        
        
    }
    
    @objc private func deleteButtonClick(button: UIButton){
        
        // 通知 -- 要传值
        NSNotificationCenter.defaultCenter().postNotificationName(kNotificationEmoticonBack, object: ["key":"value"])
        
    }
    
    //MARK:--懒加载
    private lazy var deleteButton: UIButton = {
        
        let button = UIButton(type: UIButtonType.Custom)
        
        button.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
        
        button.addTarget(self, action: "deleteButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        
        
        return button
        
    }()


}
